package com.ruoyi.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.*;
import com.ruoyi.domain.Vo.VoiceVo;
import com.ruoyi.framework.web.domain.Server;
import com.ruoyi.mapper.*;
import com.ruoyi.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class IDeviceService implements DeviceService {

    @Resource
    @Autowired
    private AdvOrdersdetailMapper ordersDetailMapper;
    @Resource
    @Autowired
    private AdvInoutstockMapper inoutstockMapper;
    @Resource
    @Autowired
    private AdvMembersMapper advMembersMapper;
    @Resource
    @Autowired
    private AdvProductsMapper advProductsMapper;
    @Resource
    @Autowired
    private AdvPlatinfosMapper advPlatinfosMapper;
    @Resource
    @Autowired
    private AdvUpgradeMapper advUpgradeMapper;
    @Resource
    @Autowired
    private AdvInoutstockMapper advInoutstockMapper;
    @Resource
    @Autowired
    private AdvDevicerelationMapper advDevicerelationMapper;

    @Resource
    @Autowired
    private Environment environment;



    /**
     * 将此会员内容订单同步为0
     *
     * @param weOpenid openId
     */
    @Override
    public void updateSyncFlagToZero(String weOpenid) {
        ordersDetailMapper.updateSyncFlagToZeroByWeOpenid(weOpenid);
    }

    /**
     * 将此会员上传的内容订单同步为1
     *
     * @param weOpenid   openId
     * @param productIds 产品id数组
     */
    @Override
    public void updateProductSyncStatus(Long[] productIds, String weOpenid) {
        ordersDetailMapper.updateSyncFlagToOneByProductId(productIds, weOpenid);
    }

    /**
     * 查询有无此设备编号以及会员账号
     *
     * @param id  产品编号
     * @param pwd md5加密的会员账号
     * @return
     */
    @Override
    public int queryPwdByInOutStock(String id, String pwd) {
        return inoutstockMapper.queryPwdByInOutStock(id, pwd);
    }

    @Override
    public Map<String, Object> syncHeartByHardware(Heart heart) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> response = new HashMap<>();

        // 校验设备编号是否为空
        if (heart.getId() == null || heart.getId().isEmpty()) {
            response.put("success", false);
            log.error("视频同步接口异常{}", "设备编号不能为空");
            response.put("message", "设备编号不能为空");
            response.put("code", 501);
            return response;
        }

        try {
            // 获取传入的数据中的产品ID列表
            List<String> incomingProductsIds = heart.getData().stream()
                    .map(Heart.Data::getProductsId)
                    .collect(Collectors.toList());

            // 获取当前设备已经同步的内容产品ID列表
            List<String> syncedProductsIds = advProductsMapper.querySyncedProductsIds(heart.getId()).stream()
                    .map(String::valueOf)
                    .collect(Collectors.toList());

            if (syncedProductsIds.isEmpty()) {
                response.put("success", false);
                response.put("message", "当前设备无内容产品");
                response.put("code", 505);
                return response;
            }

            // 遍历传入的数据，检查视频大小是否一致
            for (Heart.Data data : heart.getData()) {
                String productId = data.getProductsId();
                String incomingVideoSize = data.getVideosize();

                // 从数据库中查询视频大小
                String dbVideoSize = advProductsMapper.queryVideoSizeById(Integer.parseInt(productId));

                // 如果产品存在于数据库中但视频大小不一致，标记为 "del"
                if (syncedProductsIds.contains(productId) && !incomingVideoSize.equals(dbVideoSize)) {
                    Map<String, Object> delMap = new HashMap<>();
                    delMap.put("productsId", productId);
                    delMap.put("status", "del");
                    resultList.add(delMap);
                } else if (!syncedProductsIds.contains(productId)) {
                    // 如果传入的数据中有，但数据库中没有的产品ID，标记为 del
                    Map<String, Object> delMap = new HashMap<>();
                    delMap.put("productsId", productId);
                    delMap.put("status", "del");
                    resultList.add(delMap);
                }
            }

            // 数据库中有，但传入的数据中没有的产品ID，标记为 add
            for (String productId : syncedProductsIds) {
                if (!incomingProductsIds.contains(productId)) {
                    int i = Integer.parseInt(productId);
                    Map<String, Object> addMap = advProductsMapper.queryProductById(i);
                    addMap.put("status", "add");
                    resultList.add(addMap);
                }
            }

            advInoutstockMapper.updateOnlineByDeviceid(heart.getId());
            // 返回默认视频id和其他信息
            Integer productId = advProductsMapper.queryDefaultVideo(heart.getId());
            String restartTime = advProductsMapper.queryRestartTime(heart.getId());
            AdvInoutstock advInoutstock = advProductsMapper.queryByInoutStock(heart.getId());
            String updatetime = advProductsMapper.queryUpdatetime(heart.getId());
            AdvUpgrade advUpgrade = advUpgradeMapper.queryVersionPath(heart.getId());
            System.out.println("advInoutstock----->"+advInoutstock);
            response.put("success", true);
            response.put("message", "获取到的同步返回");
            response.put("data", resultList);
            response.put("defualtProductId", productId + "");
            response.put("reboottime", restartTime);
            response.put("updatetime", updatetime);
            if (advInoutstock!=null){
                response.put("brightness", advInoutstock.getBrightness());
                response.put("volume", advInoutstock.getVolume());
                response.put("is_online", advInoutstock.getIsOnline());
                response.put("last_hearttime", advInoutstock.getLastHearttime());
                response.put("audioswitch", "1".equals(advInoutstock.getAudioswitch()));
            }else {
                response.put("brightness", null);
                response.put("volume", null);
                response.put("is_online", null);
                response.put("last_hearttime", null);
                response.put("audioswitch", null);
            }
            if (advUpgrade != null) {
                response.put("upgradeVersion", advUpgrade.getUpgradeVersion());
                response.put("versionPath", advUpgrade.getVersionPath());
            } else {
                response.put("upgradeVersion", null);
                response.put("versionPath", null);
            }
            response.put("code", 200);
        } catch (Exception e) {
            log.error("视频同步接口异常{}",e);
            response.put("success", false);
            response.put("message", "服务器内部错误");
            response.put("code", 505);
        }
        return response;
    }

    @Override
    public Map<String, Object> SyncLiveHeartByHardware(LiveHeart heart) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Map<String, Object>> broadcasts = advMembersMapper.getBroadcasts(heart.getId());
            if (broadcasts == null || broadcasts.isEmpty()) {
                response.put("success", false);
                log.error("直播同步接口异常{}","该设备没有直播信息");
                response.put("message", "该设备没有直播信息");
                response.put("code", 505); // 204表示内容为空
                return response;
            }
            response.put("success", true);
            response.put("message", "获取到同步返回");
            response.put("data", broadcasts);
            response.put("code", 200);
        } catch (Exception e) {
            response.put("success", false);
            log.error("直播同步接口异常{}",e);
            response.put("message", "服务器内部错误");
            response.put("code", 500);
        }
        return response;
    }

    @Override
    public Map<String, Object> syncVoiceByHardware(Heart heart) {
        int code = new Random().nextInt(200);
        log.error("设备id " + heart.getId() + " 进行了心跳同步, 请求id " + code);
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> response = new HashMap<>();

        // 校验设备编号是否为空
        if (heart.getId() == null || heart.getId().isEmpty()) {
            response.put("success", false);
            log.error("音频同步接口异常{}","设备编号不能为空");
            response.put("message", "设备编号不能为空");
            response.put("code", 501);
            return response;
        }

        try {
            // 获取传入的数据中的产品ID列表
            List<String> incomingProductsIds = heart.getData().stream()
                    .map(Heart.Data::getAdvPlatinfosId)
                    .collect(Collectors.toList());

            // 获取当前设备已经同步的内容产品ID列表
            List<String> syncedProductsIds = advPlatinfosMapper.querySyncedByDeviceNo(heart.getId()).stream()
                    .map(String::valueOf)
                    .collect(Collectors.toList());

            if (syncedProductsIds.isEmpty()) {
                response.put("success", false);
                log.error("音频同步接口异常{}","当前设备无内容产品");
                response.put("message", "当前设备无内容产品");
                response.put("code", 505);
                return response;
            }

            // 传入的数据中有，但数据库中没有的产品ID，标记为 del
            for (String productId : incomingProductsIds) {
                // productId 是上传的id
                if (!syncedProductsIds.contains(productId)) {
                    int i = Integer.parseInt(productId);
                    // 如果数据库中没有这个id, 就根据这个id查询出对应的般若之声
                    Map<String, Object> delMap = advPlatinfosMapper.queryVoiceById(i);
                    if (delMap != null) {
                        // 查询到关联的信息
                        AdvDevicerelation advDevicerelation = advPlatinfosMapper.queryVoiceByDefault(i+"",heart.getId());
                        // 根据是否有值设置map属性值
                        if (advDevicerelation != null) {
                            delMap.put("default_audio", "1".equals(advDevicerelation.getIsChooseaudio()));
                            delMap.put("is_cycleplay", "1".equals(advDevicerelation.getIsCycle()));
                        } else {
                            delMap.put("default_audio", null);
                            delMap.put("is_cycleplay", null);
                        }
                    } else {
                        delMap = createEmptyMapWithProductId(productId);
                    }
                    delMap.put("status", "del");
                    resultList.add(delMap);
                }
            }

            // 数据库中有，但传入的数据中没有的产品ID，标记为 add
            for (String productId : syncedProductsIds) {
                if (!incomingProductsIds.contains(productId)) {
                    int i = Integer.parseInt(productId);
                    Map<String, Object> addMap = advPlatinfosMapper.queryVoiceById(i);
                    System.out.println("iiiiiii->"+i);
                    System.out.println("iiiiiiiddddd->"+heart.getId());
                    AdvDevicerelation advDevicerelation = advPlatinfosMapper.queryVoiceByDefault(i+"",heart.getId());
                    if (advDevicerelation != null) {
                        addMap.put("default_audio", "1".equals(advDevicerelation.getIsChooseaudio()));
                        addMap.put("is_cycleplay", "1".equals(advDevicerelation.getIsCycle()));
                    } else {
                        addMap.put("default_audio", null);
                        addMap.put("is_cycleplay", null);
                    }
                    addMap.put("status", "add");
                    resultList.add(addMap);
                }
            }

            // 额外检查：比对音频大小和音频正文大小
            for (Heart.Data data : heart.getData()) {
                String productId = data.getAdvPlatinfosId();
                String incomingMediaSize = data.getMedia_size();
                String incomingMediafileSize = data.getMediafile_size();

                // 从数据库中查询音频大小和音频正文大小
                Map<String, Object> dbData = advPlatinfosMapper.queryVoiceById(Integer.parseInt(productId));
                if (dbData != null) {
                    String dbMediaSize = (String) dbData.get("media_size");
                    String dbMediafileSize = (String) dbData.get("mediafile_size");

                    // 如果音频大小或音频正文大小不一致，标记为 "del"
                    if (!incomingMediaSize.equals(dbMediaSize) || !incomingMediafileSize.equals(dbMediafileSize)) {
                        int i = Integer.parseInt(productId);
                        Map<String, Object> delMap = advPlatinfosMapper.queryVoiceById(i);
                        if (delMap != null) {
                            AdvDevicerelation advDevicerelation = advPlatinfosMapper.queryVoiceByDefault(i+"",heart.getId());
                            if (advDevicerelation != null) {
                                delMap.put("default_audio", "1".equals(advDevicerelation.getIsChooseaudio()));
                                delMap.put("is_cycleplay", "1".equals(advDevicerelation.getIsCycle()));
                            } else {
                                delMap.put("default_audio", null);
                                delMap.put("is_cycleplay", null);
                            }
                        } else {
                            delMap = createEmptyMapWithProductId(productId);
                        }
                        delMap.put("status", "del");
                        resultList.add(delMap);
                    }else {
                        // 如果媒体大小和媒体文件大小一致，标记为 "nor"
                        Map<String, Object> norMap = new HashMap<>(dbData);
                        int i = Integer.parseInt(productId);
                        AdvDevicerelation advDevicerelation = advPlatinfosMapper.queryVoiceByDefault(i+"",heart.getId());
                        if (advDevicerelation != null) {
                            norMap.put("default_audio", "1".equals(advDevicerelation.getIsChooseaudio()));
                            norMap.put("is_cycleplay", "1".equals(advDevicerelation.getIsCycle()));
                        } else {
                            norMap.put("default_audio", null);
                            norMap.put("is_cycleplay", null);
                        }
                        norMap.put("status", "nor");
                        resultList.add(norMap);
                    }
                }
            }
            response.put("success", true);
            response.put("data", resultList);
            response.put("message", "获取到的同步返回");
            response.put("code", 200);
        } catch (Exception e) {
            log.error("音频同步接口异常{}", "服务器内部错误", e);
            response.put("success", false);
            response.put("message", "服务器内部错误");
            response.put("code", 505);
        }
        return response;
    }

    @Override
    public Map<String, Object> syncVoiceByOverTag(VoiceTag voiceTag) {
        HashMap<String, Object> resultMap = new HashMap<>();
        int i = 0;
        if (voiceTag.isAudioswitch()){
            i =  advInoutstockMapper.updateOverTagByDeviceno("1",voiceTag.getId());
        }else {
            i = advInoutstockMapper.updateOverTagByDeviceno("0",voiceTag.getId());
        }
        if (i!=0){
            resultMap.put("success",true);
        }else {
            resultMap.put("success",false);
        }
        return resultMap;
    }

    @Transactional
    @Override
    public boolean syncDeviceVideoId(VoiceVo voiceVo) {
        int i = advDevicerelationMapper.calcelDefaultVideo(voiceVo.getId());
        int i1 = advDevicerelationMapper.setDefaultVideo(voiceVo);
        return true;
    }

    @Override
    public boolean syncDeviceAudioId(VoiceVo voiceVo) {
        int i = advDevicerelationMapper.calcelDefaultAudio(voiceVo.getId());
        int i1 = advDevicerelationMapper.setDefaultAudio(voiceVo);
        return true;
    }

    private Map<String, Object> createEmptyMapWithProductId(String productId) {
        Map<String, Object> map = new HashMap<>();
        map.put("advPlatinfosId", productId);
        map.put("title", null);
        map.put("downloadurl_img", null);
        map.put("downloadurl_audio", null);
        map.put("lrcurl", null);
        map.put("infocontent", null);
        map.put("default_audio", null);
        map.put("is_cycleplay", null);
        return map;
    }

    public String getPath() {
        String hostAddress = "";
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        String url = "http://" + hostAddress + ":" + environment.getProperty("local.server.port");

        return url;
    }

}
